<template>
  <div class="visit-plan-create">
    <el-card :body-style="{ padding: '20px' }">
      <template #header>
        <div class="card-header">
          <span>走访计划创建</span>
        </div>
      </template>

      <el-form
        ref="planFormRef"
        :model="planForm"
        :rules="rules"
        label-width="120px"
      >
        <!-- 走访计划主表信息 -->
        <div class="form-section">
          <h3 class="section-title">计划基本信息</h3>

          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-model="planForm.planName"
              placeholder="请输入计划名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="客户名称" prop="customerId">
            <el-input
              v-model="planForm.customerName"
              placeholder="请选择客户"
              readonly
              @click="openCustomerModal"
              style="cursor: pointer"
            >
              <template #suffix>
                <i class="el-icon-search"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="planForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="planForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="客户经理" prop="manager">
            <el-input
              v-model="planForm.manager"
              placeholder="请输入客户经理姓名"
            ></el-input>
          </el-form-item>

          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="planForm.contactPerson"
              placeholder="请输入联系人姓名"
            ></el-input>
          </el-form-item>

          <el-form-item label="联系电话" prop="managerPhone">
            <el-input
              v-model="planForm.managerPhone"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="planForm.remark"
              type="textarea"
              placeholder="请输入备注信息"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 走访目标信息 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">走访目标</h3>
            <el-button type="primary" size="small" @click="addTarget"
              >添加目标</el-button
            >
          </div>

          <div
            v-for="(target, targetIndex) in planForm.targets"
            :key="targetIndex"
            class="target-item"
          >
            <div class="target-header">
              <span class="target-title">目标 {{ targetIndex + 1 }}</span>
              <el-button
                type="danger"
                size="small"
                @click="removeTarget(targetIndex)"
                v-if="planForm.targets.length > 1"
              >
                删除
              </el-button>
            </div>

            <el-form-item
              :label="'走访目标'"
              :prop="`targets.${targetIndex}.selectedTargets`"
              :rules="targetRules.selectedTargets"
            >
              <div class="tags-container">
                <!-- 预设标签 -->
                <span
                  v-for="presetTarget in presetTargets"
                  :key="presetTarget.value"
                  :class="[
                    'tag-item',
                    {
                      selected: target.selectedTargets.includes(
                        presetTarget.value
                      ),
                    },
                  ]"
                  @click="
                    toggleTargetSelection(targetIndex, presetTarget.value)
                  "
                >
                  {{ presetTarget.label }}
                </span>
              </div>
            </el-form-item>

            <el-form-item :label="'自定义目标'">
              <el-input
                v-model="target.customTargetInput"
                placeholder="输入自定义走访目标，按回车添加"
                @keyup.enter="addCustomTarget(targetIndex)"
                clearable
              ></el-input>

              <!-- 显示已添加的自定义目标 -->
              <div
                class="custom-tags-container"
                v-if="target.customTargets && target.customTargets.length > 0"
              >
                <span
                  v-for="(customTarget, customIndex) in target.customTargets"
                  :key="customIndex"
                  class="tag-item custom-tag"
                >
                  {{ customTarget }}
                  <i
                    class="el-icon-close"
                    @click="removeCustomTarget(targetIndex, customIndex)"
                  ></i>
                </span>
              </div>
            </el-form-item>

            <!-- 准备事项 -->
            <el-form-item :label="'准备事项'">
              <div class="tags-container">
                <!-- 预设标签 -->
                <span
                  v-for="presetPrep in presetPreparations"
                  :key="presetPrep.value"
                  :class="[
                    'tag-item',
                    {
                      selected: target.selectedPreparations.includes(
                        presetPrep.value
                      ),
                    },
                  ]"
                  @click="
                    togglePreparationSelection(targetIndex, presetPrep.value)
                  "
                >
                  {{ presetPrep.label }}
                </span>
              </div>
            </el-form-item>

            <el-form-item :label="'自定义准备事项'">
              <el-input
                v-model="target.customPreparationInput"
                placeholder="输入自定义准备事项，按回车添加"
                @keyup.enter="addCustomPreparation(targetIndex)"
                clearable
              ></el-input>

              <!-- 显示已添加的自定义准备事项 -->
              <div
                class="custom-tags-container"
                v-if="
                  target.customPreparations &&
                  target.customPreparations.length > 0
                "
              >
                <span
                  v-for="(
                    customPrep, customPrepIndex
                  ) in target.customPreparations"
                  :key="customPrepIndex"
                  class="tag-item custom-tag"
                >
                  {{ customPrep }}
                  <i
                    class="el-icon-close"
                    @click="
                      removeCustomPreparation(targetIndex, customPrepIndex)
                    "
                  ></i>
                </span>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-card>
  </div>

  <!-- 客户选择弹窗组件 -->
  <customer-select-modal
    v-model:visible="showCustomerModal"
    @customer-selected="handleCustomerSelected"
  ></customer-select-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElForm, ElMessage } from "element-plus";
import { useVisitStore } from "@/store/visit";

// 表单验证规则
import type { VisitPlan } from "@/api/visitPlan";
import CustomerSelectModal from "./CustomerSelectModal.vue";

// 定义类型接口
interface PresetItem {
  label: string;
  value: string;
}

interface Target {
  selectedTargets: string[];
  customTargetInput: string;
  customTargets: string[];
  selectedPreparations: string[];
  customPreparationInput: string;
  customPreparations: string[];
}

interface PlanForm {
  planName: string;
  planCode: string;
  customerId: string;
  customerName: string;
  startTime: string;
  endTime: string;
  manager: string;
  contactPerson: string;
  managerPhone: string;
  remark: string;
  targets: Target[];
}

interface TargetRules {
  selectedTargets: {
    validator: (rule: any, value: any, callback: Function) => void;
    trigger: string;
  }[];
}

interface Rules {
  planName: {
    required: boolean;
    message: string;
    trigger: string;
    min?: number;
    max?: number;
  }[];
  customerId: {
    required: boolean;
    message: string;
    trigger: string;
  }[];
  startTime: {
    required: boolean;
    message: string;
    trigger: string;
  }[];
  endTime: {
    required: boolean;
    message: string;
    trigger: string;
  }[];
  manager: {
    required: boolean;
    message: string;
    trigger: string;
    min?: number;
    max?: number;
  }[];
  contactPerson: {
    required: boolean;
    message: string;
    trigger: string;
    min?: number;
    max?: number;
  }[];
  managerPhone: {
    required: boolean;
    message: string;
    trigger: string;
    pattern?: RegExp;
  }[];
}

// 表单引用
const planFormRef = ref<InstanceType<typeof ElForm>>();

// 状态
const showCustomerModal = ref<boolean>(false);
const selectedCustomer = ref<any>(null);

// 使用store
const visitStore = useVisitStore();

// 表单数据
const planForm = reactive<PlanForm>({
  planName: "",
  planCode: "", // 提交时自动生成
  customerId: "",
  customerName: "",
  startTime: "",
  endTime: "",
  manager: "",
  contactPerson: "",
  managerPhone: "",
  remark: "",
  targets: [
    {
      selectedTargets: [],
      customTargetInput: "",
      customTargets: [],
      selectedPreparations: [],
      customPreparationInput: "",
      customPreparations: [],
    },
  ],
});

// 预设的走访目标标签 - 只展示两个
const presetTargets = ref<PresetItem[]>([
  { label: "产品推荐", value: "product_recommendation" },
  { label: "关键人收集", value: "key_person_collection" },
]);

// 预设的准备事项标签
const presetPreparations = ref<PresetItem[]>([
  { label: "准备产品资料", value: "prepare_product_materials" },
  { label: "准备合同", value: "prepare_contract" },
  { label: "准备演示设备", value: "prepare_demo_equipment" },
  { label: "准备名片", value: "prepare_business_cards" },
  { label: "预约会议室", value: "book_meeting_room" },
  { label: "准备样品", value: "prepare_samples" },
]);

// 表单验证规则
const rules = reactive<Rules>({
  planName: [
    { required: true, message: "请输入计划名称", trigger: "blur" },
    {
      required: true,
      min: 2,
      max: 100,
      message: "长度在 2 到 100 个字符",
      trigger: "blur",
    },
  ],
  customerId: [{ required: true, message: "请选择客户", trigger: "change" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  manager: [
    { required: true, message: "请输入客户经理姓名", trigger: "blur" },
    {
      required: true,
      min: 2,
      max: 20,
      message: "长度在 2 到 20 个字符",
      trigger: "blur",
    },
  ],
  contactPerson: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
    {
      required: true,
      min: 2,
      max: 20,
      message: "长度在 2 到 20 个字符",
      trigger: "blur",
    },
  ],
  managerPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      required: true,
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

// 目标验证规则
const targetRules = reactive<TargetRules>({
  selectedTargets: [
    {
      validator: (_rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error("请至少选择一个走访目标"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

// 获取准备事项列表
const getPreparationsList = (target: Target) => {
  const preparations: string[] = [];

  // 添加选中的预设准备事项
  if (target.selectedPreparations && target.selectedPreparations.length > 0) {
    target.selectedPreparations.forEach((prepValue) => {
      const presetPrep = presetPreparations.value.find(
        (p) => p.value === prepValue
      );
      if (presetPrep) {
        preparations.push(presetPrep.label);
      }
    });
  }

  // 添加自定义准备事项
  if (target.customPreparations && target.customPreparations.length > 0) {
    preparations.push(...target.customPreparations);
  }

  return preparations;
};

// 生成计划编号
const generatePlanCode = (): string => {
  // 获取第一个走访目标作为标签
  let targetLabel = "OTHER"; // 默认标签
  const firstTarget = planForm.targets[0];
  if (firstTarget && firstTarget.selectedTargets.length > 0) {
    const firstSelectedTarget = firstTarget.selectedTargets[0];
    if (firstSelectedTarget === "product_recommendation") {
      targetLabel = "PROD";
    } else if (firstSelectedTarget === "key_person_collection") {
      targetLabel = "KEYP";
    }
  }

  // 获取地区（这里假设从用户信息中获取，实际项目中可能需要调整）
  const region = "BJ"; // 示例：北京

  // 获取当前日期
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const dateStr = `${year}${month}${day}`;

  // 生成随机码
  const randomCode = Math.random().toString(36).substring(2, 8).toUpperCase();

  // 组合计划编号
  return `${targetLabel}-${region}-${dateStr}-${randomCode}`;
};

// 格式化走访目标为字符串
const formatVisitPurpose = (target: Target): string => {
  const purposes: string[] = [];

  // 添加选中的预设目标
  if (target.selectedTargets && target.selectedTargets.length > 0) {
    target.selectedTargets.forEach((targetValue) => {
      const presetTarget = presetTargets.value.find(
        (t) => t.value === targetValue
      );
      if (presetTarget) {
        purposes.push(presetTarget.label);
      }
    });
  }

  // 添加自定义目标
  if (target.customTargets && target.customTargets.length > 0) {
    purposes.push(...target.customTargets);
  }

  // 合并成一个字符串
  return purposes.join("、");
};

// 打开客户选择弹窗
const openCustomerModal = () => {
  showCustomerModal.value = true;
};

// 处理客户选择
const handleCustomerSelected = (customer: any) => {
  selectedCustomer.value = customer;
  planForm.customerId = customer.id;
  planForm.customerName = customer.customerName;
  showCustomerModal.value = false;
};

// 切换走访目标标签的选中状态（单选）
const toggleTargetSelection = (targetIndex: number, targetValue: string) => {
  const target = planForm.targets[targetIndex];
  const index = target.selectedTargets.indexOf(targetValue);

  if (index > -1) {
    // 如果已选中，则取消选中
    target.selectedTargets.splice(index, 1);
    // 取消选中时，需要清除相关的准备事项
    if (targetValue === "product_recommendation") {
      // 移除产品推荐相关的准备事项
      const preparationToRemove = [
        "prepare_business_cards",
        "prepare_contract",
      ];
      target.selectedPreparations = target.selectedPreparations.filter(
        (prep) => !preparationToRemove.includes(prep)
      );
    }
  } else {
    // 如果未选中，则清空当前选中的所有目标，只选择当前点击的目标（实现单选）
    // 先保存当前是否有产品推荐选中的状态
    const hadProductRecommendation = target.selectedTargets.includes(
      "product_recommendation"
    );

    // 清空所有选中的目标
    target.selectedTargets = [targetValue];

    // 根据选中的走访目标自动选择相应的准备事项
    if (targetValue === "product_recommendation") {
      // 产品推荐需要准备名片和准备合同
      if (!target.selectedPreparations.includes("prepare_business_cards")) {
        target.selectedPreparations.push("prepare_business_cards");
      }
      if (!target.selectedPreparations.includes("prepare_contract")) {
        target.selectedPreparations.push("prepare_contract");
      }
    } else if (hadProductRecommendation) {
      // 如果之前选中了产品推荐，现在切换到其他目标，则移除相关准备事项
      const preparationToRemove = [
        "prepare_business_cards",
        "prepare_contract",
      ];
      target.selectedPreparations = target.selectedPreparations.filter(
        (prep) => !preparationToRemove.includes(prep)
      );
    }
  }
};

// 切换准备事项标签的选中状态
const togglePreparationSelection = (
  targetIndex: number,
  preparationValue: string
) => {
  const target = planForm.targets[targetIndex];
  const index = target.selectedPreparations.indexOf(preparationValue);

  if (index > -1) {
    // 如果已选中，则取消选中
    target.selectedPreparations.splice(index, 1);
  } else {
    // 如果未选中，则添加选中
    target.selectedPreparations.push(preparationValue);
  }
};

// 添加自定义目标
const addCustomTarget = (targetIndex: number) => {
  const target = planForm.targets[targetIndex];
  const customTargetText =
    target.customTargetInput && target.customTargetInput.trim();

  if (customTargetText && !target.customTargets.includes(customTargetText)) {
    target.customTargets.push(customTargetText);
    target.customTargetInput = ""; // 清空输入框
  }
};

// 移除自定义目标
const removeCustomTarget = (targetIndex: number, customTargetIndex: number) => {
  planForm.targets[targetIndex].customTargets.splice(customTargetIndex, 1);
};

// 添加自定义准备事项
const addCustomPreparation = (targetIndex: number) => {
  const target = planForm.targets[targetIndex];
  const customPrepText =
    target.customPreparationInput && target.customPreparationInput.trim();

  if (customPrepText && !target.customPreparations.includes(customPrepText)) {
    target.customPreparations.push(customPrepText);
    target.customPreparationInput = ""; // 清空输入框
  }
};

// 移除自定义准备事项
const removeCustomPreparation = (
  targetIndex: number,
  customPrepIndex: number
) => {
  planForm.targets[targetIndex].customPreparations.splice(customPrepIndex, 1);
};

// 添加走访目标
const addTarget = () => {
  planForm.targets.push({
    selectedTargets: [],
    customTargetInput: "",
    customTargets: [],
    selectedPreparations: [],
    customPreparationInput: "",
    customPreparations: [],
  });
};

// 删除走访目标
const removeTarget = (index: number) => {
  planForm.targets.splice(index, 1);
};

// 重置表单
const resetForm = () => {
  planFormRef.value?.resetFields();

  // 重置表单数据
  Object.assign(planForm, {
    planName: "",
    planCode: "",
    customerId: "",
    customerName: "",
    startTime: "",
    endTime: "",
    manager: "",
    contactPerson: "",
    managerPhone: "",
    remark: "",
    targets: [
      {
        selectedTargets: [],
        customTargetInput: "",
        customTargets: [],
        selectedPreparations: [],
        customPreparationInput: "",
        customPreparations: [],
      },
    ],
  });
};

// 提交表单
const submitForm = () => {
  // 自动生成计划编号
  planForm.planCode = generatePlanCode();

  planFormRef.value?.validate(async (valid) => {
    if (valid) {
      // 构建提交数据，匹配后端的VisitPlanDTO结构
      const visitPlanDTO = {
        planName: planForm.planName,
        planCode: planForm.planCode,
        customerId: planForm.customerId,
        customerName: planForm.customerName,
        startTime: planForm.startTime,
        endTime: planForm.endTime,
        manager: planForm.manager,
        contactPerson: planForm.contactPerson,
        managerPhone: planForm.managerPhone,
        status: "待完成", // 默认状态为待完成
        remark: planForm.remark,
        targets: planForm.targets.map((target) => ({
          targetName: formatVisitPurpose(target),
          targetType: "走访目标",
          targetValue: getPreparationsList(target).join(","),
        })),
      } as VisitPlan;

      try {
        // 使用store中的方法创建走访计划
        const result = await visitStore.createVisitPlan(visitPlanDTO);

        if (result) {
          ElMessage.success("走访计划创建成功");
          resetForm();
          // 可以在这里添加跳转逻辑
        }
      } catch (error) {
        ElMessage.error("走访计划创建失败：" + (error as Error).message);
        console.error("创建走访计划失败：", error);
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.visit-plan-create {
  padding: 20px;
  font-size: 14px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .form-section {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 4px;
    
    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 15px;
    }
    
    .target-item {
      margin-bottom: 15px;
      padding: 15px;
      background-color: #ffffff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      }
      
      .target-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
        
        .target-title {
          font-size: 14px;
          font-weight: bold;
          color: #303133;
        }
      }
      
      .preparation-section {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px dashed #e4e7ed;
        
        .preparation-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          
          .preparation-title {
            font-size: 14px;
            color: #303133;
            font-weight: bold;
          }
        }
        
        .preparation-item {
          margin-bottom: 10px;
          
          .preparation-content {
            display: flex;
            align-items: center;
          }
        }
      }
    }
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }
    
    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 10px;
      padding: 10px;
      background-color: #ffffff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
    }
    
    .custom-tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 10px;
      padding: 10px;
      background-color: #ffffff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
    }
  }
  
  .form-actions {
    margin-top: 20px;
    padding: 15px 0;
    text-align: right;
    border-top: 1px solid #e4e7ed;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
}

.tag-item {
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  background-color: #f0f2f5;
  border-radius: 16px;
  color: #606266;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background-color: #e6f7ff;
    border-color: #409eff;
  }
  
  &.selected {
    background-color: #409eff;
    color: #ffffff;
  }
  
  &.custom-tag {
    background-color: #52c41a;
    color: #ffffff;
    
    &:hover {
      background-color: #73d13d;
    }
  }
  
  .el-icon-close {
    margin-left: 4px;
    font-size: 10px;
    cursor: pointer;
  }
}

/* 响应式布局 */
@media (max-width: 768px) {
  .visit-plan-create {
    padding: 10px;
    
    .form-section {
      padding: 15px;
      
      .tags-container,
      .custom-tags-container {
        gap: 8px;
        padding: 8px;
      }
    }
  }
}
</style>
